import React, { useState, useMemo, useEffect } from 'react'
import { Button, Select, Tooltip, ColorPicker, Modal, Input, Space, Divider, Dropdown, message } from 'antd'
import type { MenuProps } from 'antd'
import type { Editor } from '@tiptap/react'
import type { Color } from 'antd/es/color-picker'
import {
  BoldOutlined,
  ItalicOutlined,
  UnderlineOutlined,
  StrikethroughOutlined,
  CodeOutlined,
  OrderedListOutlined,
  UnorderedListOutlined,
  CheckSquareOutlined,
  AlignLeftOutlined,
  AlignCenterOutlined,
  AlignRightOutlined,
  FontColorsOutlined,
  BgColorsOutlined,
  LinkOutlined,
  PictureOutlined,
  TableOutlined,
  BlockOutlined,
  ClearOutlined,
  UndoOutlined,
  RedoOutlined,
  ExportOutlined,
  SaveOutlined,
  DownOutlined
} from '@ant-design/icons'
import { exportToMarkdown, exportToHtml, copyAsMarkdown, copyAsPlainText } from '../../../utils/export'
import { htmlToMarkdown } from '../../../utils/exportUtils'
import { ExportButton } from '../../Export/ExportButton'
import './MenuBar.css'

export interface MenuBarProps {
  editor: Editor
  onSave?: () => void
  /** 文档标题，用于导出文件名 */
  documentTitle?: string
}

/**
 * 富文本工具栏组件
 * 提供所有格式化功能的用户界面
 */
export const MenuBar: React.FC<MenuBarProps> = ({ editor, onSave, documentTitle }) => {
  const [linkModalVisible, setLinkModalVisible] = useState(false)
  const [linkUrl, setLinkUrl] = useState('')
  const [imageModalVisible, setImageModalVisible] = useState(false)
  const [imageUrl, setImageUrl] = useState('')
  const [currentHeading, setCurrentHeading] = useState(0)
  const [textColor, setTextColor] = useState('#000000')
  const [highlightColor, setHighlightColor] = useState('#ffff00')

  if (!editor) {
    return null
  }

  // 获取当前标题层级
  const getCurrentHeading = (): number => {
    for (let level = 1; level <= 6; level++) {
      if (editor.isActive('heading', { level })) {
        return level
      }
    }
    return 0 // 正文
  }

  // 监听编辑器更新，更新当前标题状态和颜色状态
  useEffect(() => {
    if (!editor) return

    const updateStates = () => {
      // 更新标题
      const newHeading = getCurrentHeading()
      setCurrentHeading(prev => prev !== newHeading ? newHeading : prev)

      // 更新文字颜色
      const newTextColor = editor.getAttributes('textStyle').color || '#000000'
      setTextColor(prev => prev !== newTextColor ? newTextColor : prev)

      // 更新高亮颜色
      const newHighlightColor = editor.getAttributes('highlight').color || '#ffff00'
      setHighlightColor(prev => prev !== newHighlightColor ? newHighlightColor : prev)
    }

    // 初始化时更新一次
    updateStates()

    // 只监听光标位置变化，不监听transaction（太频繁）
    editor.on('selectionUpdate', updateStates)

    return () => {
      editor.off('selectionUpdate', updateStates)
    }
  }, [editor])

  // 设置标题层级
  const setHeading = (level: number) => {
    if (level === 0) {
      editor.chain().focus().setParagraph().run()
    } else {
      editor.chain().focus().setHeading({ level: level as 1 | 2 | 3 | 4 | 5 | 6 }).run()
    }
  }

  // 插入链接
  const handleInsertLink = () => {
    const currentUrl = editor.getAttributes('link').href || ''
    setLinkUrl(currentUrl)
    setLinkModalVisible(true)
  }

  const handleLinkOk = () => {
    if (linkUrl) {
      editor
        .chain()
        .focus()
        .extendMarkRange('link')
        .setLink({ href: linkUrl })
        .run()
    } else {
      editor.chain().focus().unsetLink().run()
    }
    setLinkModalVisible(false)
    setLinkUrl('')
  }

  // 插入图片
  const handleInsertImage = () => {
    setImageModalVisible(true)
  }

  const handleImageOk = () => {
    if (imageUrl) {
      editor.chain().focus().setImage({ src: imageUrl }).run()
    }
    setImageModalVisible(false)
    setImageUrl('')
  }

  // 颜色处理
  const handleTextColorChange = (color: Color) => {
    const hexColor = color.toHexString()
    setTextColor(hexColor)
    editor.chain().focus().setColor(hexColor).run()
  }

  const handleHighlightColorChange = (color: Color) => {
    const hexColor = color.toHexString()
    setHighlightColor(hexColor)
    editor.chain().focus().toggleHighlight({ color: hexColor }).run()
  }

  // 将HTML转换为Markdown格式的内容
  const getContentForExport = (): string => {
    const html = editor.getHTML()
    const filename = documentTitle?.trim() || '未命名文档'

    // 在内容前添加文档标题
    const htmlWithTitle = `<h1>${filename}</h1>${html}`
    const markdown = htmlToMarkdown(htmlWithTitle)

    return markdown
  }

  const handleExportComplete = (filename: string, format: string) => {
    message.success(`${format.toUpperCase()}导出成功: ${filename}`)
  }
  const exportMenuItems: MenuProps['items'] = useMemo(() => {
    // 使用文档标题或默认值
    const filename = documentTitle?.trim() || '未命名文档'

    return [
      {
        key: 'markdown',
        label: '导出为 Markdown',
        onClick: () => {
          try {
            const html = editor.getHTML()
            // 在内容前添加文档标题
            const htmlWithTitle = `<h1>${filename}</h1>${html}`
            exportToMarkdown(htmlWithTitle, filename)
            message.success('Markdown文件导出成功')
          } catch (error) {
            message.error('导出失败')
          }
        }
      },
      {
        key: 'html',
        label: '导出为 HTML',
        onClick: () => {
          try {
            const html = editor.getHTML()
            // 在内容前添加文档标题
            const htmlWithTitle = `<h1>${filename}</h1>${html}`
            exportToHtml(htmlWithTitle, filename)
            message.success('HTML文件导出成功')
          } catch (error) {
            message.error('导出失败')
          }
        }
      },
      {
        type: 'divider'
      },
      {
        key: 'copy-markdown',
        label: '复制为 Markdown',
        onClick: async () => {
          try {
            const html = editor.getHTML()
            // 在内容前添加文档标题
            const htmlWithTitle = `<h1>${filename}</h1>${html}`
            await copyAsMarkdown(htmlWithTitle)
            message.success('已复制Markdown到剪贴板')
          } catch (error) {
            message.error('复制失败')
          }
        }
      },
      {
        key: 'copy-text',
        label: '复制为纯文本',
        onClick: async () => {
          try {
            const html = editor.getHTML()
            // 在内容前添加文档标题
            const htmlWithTitle = `<h1>${filename}</h1>${html}`
            await copyAsPlainText(htmlWithTitle)
            message.success('已复制纯文本到剪贴板')
          } catch (error) {
            message.error('复制失败')
          }
        }
      }
    ]
  }, [editor, documentTitle])

  return (
    <div className="menu-bar">
      {/* 保存按钮 */}
      {onSave && (
        <>
          <div className="menu-group">
            <Tooltip title="保存 (Ctrl+S)">
              <Button
                type="primary"
                size="small"
                icon={<SaveOutlined />}
                onClick={onSave}
              >
                保存
              </Button>
            </Tooltip>
          </div>
          <Divider type="vertical" />
        </>
      )}

      {/* 文本格式 */}
      <div className="menu-group">
        <Tooltip title="粗体 (Ctrl+B)">
          <Button
            type={editor.isActive('bold') ? 'primary' : 'text'}
            size="small"
            icon={<BoldOutlined />}
            onClick={() => editor.chain().focus().toggleBold().run()}
          />
        </Tooltip>

        <Tooltip title="斜体 (Ctrl+I)">
          <Button
            type={editor.isActive('italic') ? 'primary' : 'text'}
            size="small"
            icon={<ItalicOutlined />}
            onClick={() => editor.chain().focus().toggleItalic().run()}
          />
        </Tooltip>

        <Tooltip title="下划线 (Ctrl+U)">
          <Button
            type={editor.isActive('underline') ? 'primary' : 'text'}
            size="small"
            icon={<UnderlineOutlined />}
            onClick={() => editor.chain().focus().toggleUnderline().run()}
          />
        </Tooltip>

        <Tooltip title="删除线">
          <Button
            type={editor.isActive('strike') ? 'primary' : 'text'}
            size="small"
            icon={<StrikethroughOutlined />}
            onClick={() => editor.chain().focus().toggleStrike().run()}
          />
        </Tooltip>

        <Tooltip title="行内代码">
          <Button
            type={editor.isActive('code') ? 'primary' : 'text'}
            size="small"
            icon={<CodeOutlined />}
            onClick={() => editor.chain().focus().toggleCode().run()}
          />
        </Tooltip>
      </div>

      <Divider type="vertical" />

      {/* 标题层级 */}
      <div className="menu-group">
        <Select
          value={currentHeading}
          onChange={setHeading}
          style={{ width: 100 }}
          size="small"
          options={[
            { label: '正文', value: 0 },
            { label: '标题 1', value: 1 },
            { label: '标题 2', value: 2 },
            { label: '标题 3', value: 3 },
            { label: '标题 4', value: 4 },
            { label: '标题 5', value: 5 },
            { label: '标题 6', value: 6 }
          ]}
        />
      </div>

      <Divider type="vertical" />

      {/* 列表 */}
      <div className="menu-group">
        <Tooltip title="有序列表">
          <Button
            type={editor.isActive('orderedList') ? 'primary' : 'text'}
            size="small"
            icon={<OrderedListOutlined />}
            onClick={() => editor.chain().focus().toggleOrderedList().run()}
          />
        </Tooltip>

        <Tooltip title="无序列表">
          <Button
            type={editor.isActive('bulletList') ? 'primary' : 'text'}
            size="small"
            icon={<UnorderedListOutlined />}
            onClick={() => editor.chain().focus().toggleBulletList().run()}
          />
        </Tooltip>

        <Tooltip title="任务列表">
          <Button
            type={editor.isActive('taskList') ? 'primary' : 'text'}
            size="small"
            icon={<CheckSquareOutlined />}
            onClick={() => editor.chain().focus().toggleTaskList().run()}
          />
        </Tooltip>
      </div>

      <Divider type="vertical" />

      {/* 对齐方式 */}
      <div className="menu-group">
        <Tooltip title="左对齐">
          <Button
            type={editor.isActive({ textAlign: 'left' }) ? 'primary' : 'text'}
            size="small"
            icon={<AlignLeftOutlined />}
            onClick={() => editor.chain().focus().setTextAlign('left').run()}
          />
        </Tooltip>

        <Tooltip title="居中">
          <Button
            type={editor.isActive({ textAlign: 'center' }) ? 'primary' : 'text'}
            size="small"
            icon={<AlignCenterOutlined />}
            onClick={() => editor.chain().focus().setTextAlign('center').run()}
          />
        </Tooltip>

        <Tooltip title="右对齐">
          <Button
            type={editor.isActive({ textAlign: 'right' }) ? 'primary' : 'text'}
            size="small"
            icon={<AlignRightOutlined />}
            onClick={() => editor.chain().focus().setTextAlign('right').run()}
          />
        </Tooltip>
      </div>

      <Divider type="vertical" />

      {/* 颜色 */}
      <div className="menu-group">
        <Tooltip title="文字颜色">
          <ColorPicker
            size="small"
            value={textColor}
            onChange={handleTextColorChange}
          >
            <Button size="small" icon={<FontColorsOutlined />} />
          </ColorPicker>
        </Tooltip>

        <Tooltip title="背景色">
          <ColorPicker
            size="small"
            value={highlightColor}
            onChange={handleHighlightColorChange}
          >
            <Button size="small" icon={<BgColorsOutlined />} />
          </ColorPicker>
        </Tooltip>
      </div>

      <Divider type="vertical" />

      {/* 插入 */}
      <div className="menu-group">
        <Tooltip title="插入链接">
          <Button
            type={editor.isActive('link') ? 'primary' : 'text'}
            size="small"
            icon={<LinkOutlined />}
            onClick={handleInsertLink}
          />
        </Tooltip>

        <Tooltip title="插入图片">
          <Button
            type="text"
            size="small"
            icon={<PictureOutlined />}
            onClick={handleInsertImage}
          />
        </Tooltip>

        <Tooltip title="插入表格">
          <Button
            type="text"
            size="small"
            icon={<TableOutlined />}
            onClick={() => editor.chain().focus().insertTable({ rows: 3, cols: 3 }).run()}
          />
        </Tooltip>

        <Tooltip title="代码块">
          <Button
            type={editor.isActive('codeBlock') ? 'primary' : 'text'}
            size="small"
            icon={<BlockOutlined />}
            onClick={() => editor.chain().focus().toggleCodeBlock().run()}
          />
        </Tooltip>
      </div>

      <Divider type="vertical" />

      {/* 其他 */}
      <div className="menu-group">
        <Tooltip title="清除格式">
          <Button
            type="text"
            size="small"
            icon={<ClearOutlined />}
            onClick={() => editor.chain().focus().unsetAllMarks().clearNodes().run()}
          />
        </Tooltip>

        <Tooltip title="撤销 (Ctrl+Z)">
          <Button
            type="text"
            size="small"
            icon={<UndoOutlined />}
            disabled={!editor.can().undo()}
            onClick={() => editor.chain().focus().undo().run()}
          />
        </Tooltip>

        <Tooltip title="重做 (Ctrl+Y)">
          <Button
            type="text"
            size="small"
            icon={<RedoOutlined />}
            disabled={!editor.can().redo()}
            onClick={() => editor.chain().focus().redo().run()}
          />
        </Tooltip>
      </div>

      <Divider type="vertical" />

      {/* 导出 */}
      <div className="menu-group">
        <Space size="small">
          {/* 新的PDF/Word导出按钮 */}
          <ExportButton
            content={getContentForExport()}
            onExportComplete={handleExportComplete}
          />
          
          {/* 原有的Markdown/HTML导出按钮 */}
          <Dropdown menu={{ items: exportMenuItems }} placement="bottomRight">
            <Button size="small" icon={<ExportOutlined />}>
              其他格式 <DownOutlined />
            </Button>
          </Dropdown>
        </Space>
      </div>

      {/* 插入链接对话框 */}
      <Modal
        title="插入链接"
        open={linkModalVisible}
        onOk={handleLinkOk}
        onCancel={() => {
          setLinkModalVisible(false)
          setLinkUrl('')
        }}
        okText="确定"
        cancelText="取消"
        width={400}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Input
            placeholder="请输入链接地址"
            value={linkUrl}
            onChange={(e) => setLinkUrl(e.target.value)}
            onPressEnter={handleLinkOk}
          />
          {editor.isActive('link') && (
            <Button
              danger
              size="small"
              onClick={() => {
                editor.chain().focus().unsetLink().run()
                setLinkModalVisible(false)
                setLinkUrl('')
              }}
            >
              移除链接
            </Button>
          )}
        </Space>
      </Modal>

      {/* 插入图片对话框 */}
      <Modal
        title="插入图片"
        open={imageModalVisible}
        onOk={handleImageOk}
        onCancel={() => {
          setImageModalVisible(false)
          setImageUrl('')
        }}
        okText="确定"
        cancelText="取消"
        width={400}
      >
        <Input
          placeholder="请输入图片地址"
          value={imageUrl}
          onChange={(e) => setImageUrl(e.target.value)}
          onPressEnter={handleImageOk}
        />
      </Modal>
    </div>
  )
}

export default MenuBar
